/*
 * =====================================================================================
 *
 *       Filename:  cl_utils.cxx
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  10/12/2010 09:03:33 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Chen Ken (Ken), zlchen.ken@gmail.com
 *        Company:  EMC
 *
 * =====================================================================================
 */

#include <sys/time.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <unistd.h>
#include "cl_utils.hxx"

namespace neo
{

namespace
{
  const int CL_CACHE_LINE_SIZE = 64;
}

int clMSleep(unsigned long uSeconds)
{
	struct timeval tv;
	tv.tv_sec = uSeconds/1000000;
	tv.tv_usec = uSeconds%1000000;

  return ::select(0, NULL, NULL, NULL, &tv);
}

int clCacheLineSize(void)
{
  long lineSize = ::sysconf(_SC_LEVEL1_DCACHE_LINESIZE);  
  if(lineSize > 0)
  {
    return lineSize;
  }
  else
  {
    return CL_CACHE_LINE_SIZE;
  }
}

int clOnlineProcessorNum(void)
{
   long cpuNum = ::sysconf(_SC_NPROCESSORS_ONLN);
   if(cpuNum < 0)
   {
     return 0;
   }
   return cpuNum;
}

int clMaxFdSize(void)
{
  int fdsize = ::getdtablesize();
#ifdef RLIMIT_NOFILE
   struct rlimit rl;
   if(::getrlimit(RLIMIT_NOFILE, &rl) == 0)
	 {
		 fdsize = rl.rlim_cur;
		 if(rl.rlim_max == RLIM_INFINITY)
		 {
       rl.rlim_cur = 8192;
		 }
     else if(rl.rlim_max > rl.rlim_cur)
		 {
       rl.rlim_cur = rl.rlim_max;
		 }

		 if(setrlimit( RLIMIT_NOFILE, &rl) == 0)
		 {
       fdsize = rl.rlim_cur;
		 }
	 }
#endif
   if(fdsize <= 0)
	 {
		 fdsize = 8192;
	 }
   return fdsize;
}

} // neo

